package com.zhq.okhttp.progress;

import android.content.Context;
import android.content.DialogInterface;
import android.os.Handler;
import android.os.Message;

import com.zhq.widget.popupwindow.LoadingView;


public class ProgressDialogHandler extends Handler {
    public static final int SHOW_PROGRESS_DIALOG = 1;
    public static final int DISMISS_PROGRESS_DIALOG = 2;
    private LoadingView loadingView;
    private Context context;
    private boolean cancelable;
    private String message;
    private ProgressCancelListener mProgressCancelListener;

    public ProgressDialogHandler(Context context, ProgressCancelListener mProgressCancelListener,
                                 String message, boolean cancelable) {
        super();
        this.context = context;
        this.message = message;
        this.mProgressCancelListener = mProgressCancelListener;
        this.cancelable = cancelable;
    }

    private void initProgressDialog() {
        if (loadingView == null && context != null) {
            loadingView = new LoadingView(context);
            loadingView.setLoadContent(message);
            if (cancelable) {
                loadingView.setCanceledOnTouchOutside(true);
                loadingView.setOnCancelListener(new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {
                        mProgressCancelListener.onCancelProgress();
                    }
                });
            }
            if (!loadingView.isShowing()) {
                loadingView.show();
            }
        }
    }

    private void dismissProgressDialog() {
        if (loadingView != null) {
            loadingView.dismiss();
            loadingView = null;
            mProgressCancelListener = null;
        }
    }

    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {
            case SHOW_PROGRESS_DIALOG:
                initProgressDialog();
                break;
            case DISMISS_PROGRESS_DIALOG:
                dismissProgressDialog();
                break;
        }
    }

}
